// 更新可见性
document.querySelectorAll('.visibility-select').forEach(select => {
    select.addEventListener('change', function() {
        const coupleId = this.dataset.id;
        const visibility = this.value;
        
        fetch(`/admin/couples/${coupleId}/update`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            },
            body: `visibility=${visibility}`
        })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                // 成功时不刷新页面
            } else {
                alert(data.message || '更新失败');
                location.reload();
            }
        })
        .catch(error => {
            console.error('Error:', error);
            alert('更新失败，请重试');
            location.reload();
        });
    });
});

// 更新点赞数
document.querySelectorAll('.likes-input').forEach(input => {
    let timeout;
    input.addEventListener('input', function() {
        clearTimeout(timeout);
        const coupleId = this.dataset.id;
        const likes = this.value;
        
        timeout = setTimeout(() => {
            fetch(`/admin/couples/${coupleId}/update`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/x-www-form-urlencoded'
                },
                body: `likes=${likes}`
            })
            .then(response => response.json())
            .then(data => {
                if (!data.success) {
                    alert(data.message || '更新失败');
                    location.reload();
                }
            })
            .catch(error => {
                console.error('Error:', error);
                alert('更新失败，请重试');
                location.reload();
            });
        }, 500);
    });
});

// 删除情侣
function deleteCouple(coupleId) {
    if (!confirm('确定要删除该情侣吗？此操作不可恢复！')) {
        return;
    }
    
    fetch(`/admin/couples/${coupleId}/delete`, {
        method: 'POST'
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('删除成功');
            location.reload();
        } else {
            alert(data.message || '删除失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('删除失败，请重试');
    });
}

// 关闭模态框
function closeModal(modalId) {
    document.getElementById(modalId).style.display = 'none';
}

// 显示加载遮罩
function showLoading() {
    document.querySelector('.loading-mask').style.display = 'flex';
}

// 隐藏加载遮罩
function hideLoading() {
    document.querySelector('.loading-mask').style.display = 'none';
}

// 生成AI总结
async function generateAISummary(coupleId) {
    try {
        showLoading();  // 显示加载遮罩
        
        // 先获取timeline数据
        const response = await fetch(`/admin/couples/${coupleId}/timelines`);
        const data = await response.json();
        
        if (!data.success) {
            hideLoading();  // 隐藏加载遮罩
            alert(data.message || '获取数据失败');
            return;
        }
        
        if (!data.timelines || data.timelines.length === 0) {
            hideLoading();  // 隐藏加载遮罩
            alert('该情侣暂无记录可供总结');
            return;
        }
        
        // 调用AI生成总结
        const aiResponse = await fetch(`/admin/couples/${coupleId}/ai-summary`, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                timelines: data.timelines
            })
        });
        
        const aiData = await aiResponse.json();
        if (!aiData.success) {
            hideLoading();  // 隐藏加载遮罩
            alert(aiData.message || 'AI总结生成失败');
            return;
        }
        
        // 显示编辑模态框
        const form = document.getElementById('aiSummaryForm');
        form.coupleId.value = coupleId;
        form.content.value = aiData.content;
        document.getElementById('aiSummaryModal').style.display = 'block';
        
    } catch (error) {
        console.error('Error:', error);
        alert('操作失败，请重试');
    } finally {
        hideLoading();  // 确保无论成功失败都隐藏加载遮罩
    }
}

// 发布AI总结为评论
document.getElementById('aiSummaryForm').addEventListener('submit', function(e) {
    e.preventDefault();
    
    const formData = new FormData(this);
    const coupleId = formData.get('coupleId');
    const content = formData.get('content');
    
    fetch(`/admin/couples/${coupleId}/comment`, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json'
        },
        body: JSON.stringify({
            content: content
        })
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            alert('评论发布成功');
            closeModal('aiSummaryModal');
        } else {
            alert(data.message || '评论发布失败');
        }
    })
    .catch(error => {
        console.error('Error:', error);
        alert('评论发布失败，请重试');
    });
});
 